<template>
	<view>
		<view class="boxTemplate">
			<view v-for="(item,index) in recharge" :key="index" style="margin-left: 10rpx;">
				<!-- @click="createOrder(item,index)" -->
				<view class="Scheme" v-if="item.subject != '单剧会员' || item.tv_id == tv_id">
					<view class="Schemecontentss"
						v-if="item.subject == '月度会员' || item.subject == '季度会员' || item.subject == '年度会员'"
						@click="newRecharge(item,index)">
						<view class="Judge">{{item.subject}}</view>
						<view class="RechargeAmount">￥{{item.recharge_amount / 100}}</view>
						<view class="RechargeText">{{item.recharge_text}}</view>
					</view>
					<view class="Schemecontentss" v-else-if="item.subject == '单剧会员' && item.tv_id == tv_id"
						@click="newRecharge(item,index)">
						<view class="Judge">解锁全集</view>
						<view class="RechargeAmount">￥{{item.recharge_amount / 100}}</view>
						<view class="RechargeText">{{item.recharge_text}}</view>
					</view>
					<view class="Schemecontentss" v-else-if="item.subject == '自定义会员'" @click="newRecharge(item,index)">
						<view class="Judge">VIP会员</view>
						<view class="RechargeAmount">￥{{item.recharge_amount / 100}}</view>
						<view class="RechargeText">{{item.recharge_text}}</view>
					</view>
					<view class="Schemecontent" v-else-if="item.judge == true  && !item.tv_id"
						@click="newRecharge(item,index)">
						<view class="Judge">特惠</view>
						<view class="RechargeAmount">￥{{item.recharge_amount / 100}}</view>
						<view class="GiveBean" v-if="item.give_bean">多送{{item.give_bean}}豆</view>
						<view class="RechargeText">{{item.recharge_text}}</view>
						<view class="PercentageUser">{{item.percentage_user || ''}}</view>
					</view>

					<view class="Schemecontents" v-else-if="item.judge == false  && !item.tv_id"
						@click="newRecharge(item,index)">
						<view class="RechargeAmount">￥{{item.recharge_amount / 100}}</view>
						<view class="GiveBean" v-if="item.give_bean">多送{{item.give_bean}}豆</view>
						<view class="RechargeText">{{item.recharge_text}}</view>
					</view>

				</view>
			</view>

			<u-gap height="30rpx"></u-gap>
			<view>
				<view class="explanation">充值说明：</view>
				<view class="" v-for="(item, index) in splitText" :key="index">
					<view class="explanation">{{index+1 }}.{{ item }}</view>
				</view>
			</view>
		</view>


		<view v-if="vk.vuex.get('$user.userInfo._id')">
			<vk-uni-pay ref="vkPay" :query-payment-action="vkPay.queryPaymentAction" :status.sync="vkPay.status"
				:code-url.sync="vkPay.codeUrl" :page-show="vkPay.pageShow" :polling="vkPay.polling"></vk-uni-pay>
		</view>

		<!-- 客服按钮 -->
		<button class="ttbuttona" open-type="im" :data-im-id="vk.vuex.get('$app.dykefu')" bindim="imCallback"
			binderror="onimError" shape="circle">
			<u-icon name="kefu-ermai" color="#c8c8c0" size="32"></u-icon>
		</button>
	</view>
</template>

<script>
	import md5 from "@/pages/MD5.js"
	const db = uniCloud.database();
	const _ = db.command;
	export default {
		name: "rechargelist",
		props: ['recharge', 'tv_name', 'tv_id'],
		data() {
			return {
				datam: '',
				byteAuthorization: '',
				splitText: [], //充值说明
				access_token: "",
				activeColor: 100,
				balance: 0,
				info: {},
				imId: '', //抖音IM号
				// 表单请求数据
				form1: {
					provider: "wxpay",
					openid: "",
					total_fee: 1,
					out_trade_no: "",
					subject: "充值金豆",
					body: "得XX金豆",
					type: "recharge"
				}
			};
		},
		created() {
			this.imId = vk.vuex.get('$app.dykefu')

			this.splitText = this.splitTextByNumber(vk.vuex.get('$app.appinfo.recharge_instructions'));


			let that = this;
			//判断用户登录状态(有id且token有效)
			if (uni.vk.checkToken()) {
				// uni.vk.userCenter.getCurrentUserInfo({
				// 	success: (data) => {
				// 		uni.request({ //请求获取accessToken
				// 			url: 'https://developer.toutiao.com/api/apps/v2/token',
				// 			method: "POST",
				// 			data: {
				// 				appid: uni.vk.vuex.get('$app.appid'), //小程序的AppID
				// 				secret: uni.vk.vuex.get('$app.appinfo').appsecret, //小程序的AppSecret
				// 				grant_type: 'client_credential'
				// 			},
				// 			success: (res) => {
				// 				console.log("tokenres=", res.data.data.access_token);
				// 				uni.vk.vuex.set('$app.access_token', res.data.data.access_token)
				// 				that.access_token = res.data.data.access_token
				// 			}
				// 		});
				// 	}
				// });
			} else {
				uni.vk.myfn.ttlogin();
			}

			this.form1.openid = vk.vuex.get('$user.userInfo.tt_openid');
		},
		methods: {

			//处理充值说明
			splitTextByNumber(text) {
				const regex = /\d+\./g; // 匹配数字和句号的正则表达式
				return text.split(regex).filter(item => item !== ''); // 使用split()方法分割文本，并过滤掉空字符串
			},
			async newRecharge(item, index) {
				this.activeColor = index
				uni.showLoading({
					title: "数据校验中..."
				});
				//把当前选中的充值套餐单独存放
				this.currentRecharge = item;
				//生成订单号
				this.form1.out_trade_no = uni.vk.pubfn.createOrderNo("NO")

				//退款单号
				this.form1.out_refund_no = uni.vk.pubfn.createOrderNo("ext_")
				//未获取到用户ID则失败
				if (!uni.vk.vuex.get('$user.userInfo._id')) {
					uni.showToast({
						title: "获取信息失败",
						icon: "error"
					})
					return;
				}


				vk.callFunction({
					url: 'client/pay/kh/ttmakeRecharge',
					title: '请求中...',
					data: {
						out_trade_no: this.form1.out_trade_no,
						out_refund_no: this.form1.out_refund_no,
						item,
						tv_id: this.tv_id || "直充",
						tv_name: this.tv_name || "直充", //记录本次充值来自哪部剧，无来源就是直充
						appid: vk.vuex.get('$app.appid'),
						appname: vk.vuex.get('$app.appname'),

					},
					success: (data) => {
						console.log("创建订单成功", data);
						let add_id = data.add_order.id;
						// this.checkData(item,add_id)
						this.oderlist(item, add_id)
					}
				});
				this.$emit('clickRecharge', 1)
			},

			async oderlist(item, add_id) {
				//从数据库里查找刚添加的订单数据，确保已提交到数据库
				let that = this
				const order_info = await db.collection('a_recharge').doc(add_id).get()
				//找到则发起订单，未找到则提示失败
				if (order_info.result.data.length > 0) {

					//获取签名
					await vk.callFunction({
						url: 'client/pay/kh/paysignature',
						title: '请求中...',
						data: {
							appId: vk.vuex.get('$app.appid'),
							outOrderNo: this.form1.out_trade_no,
							recharge_amount: item.recharge_amount,
							subject: item.subject

						},
						success: (data) => {
							console.log("获取的签名参数", data.byteAuthorization);
							this.byteAuthorization = data.byteAuthorization
							console.log("data参数", data.datam);
							// this.datam=JSON.parse(data.datam)
							this.datam = data.datam
						}
					});
					// JSON.stringify(this.datam)
					console.log("看看服务端传过来的data", this.datam);

					// console.log("看看系统",vk.vuex.get('$app.osName')=='ios');

					// if(vk.vuex.get('$app.osName')=='ios'){

					// }

					await tt.requestOrder({
						header: {
							"Content-Type": "application/json",
						},
						data: JSON.stringify(this.datam),
						byteAuthorization: this.byteAuthorization,
						success: (res) => {
							console.log('拉起收银台成功', res.orderId);

							if (vk.vuex.get('$app.osName') == 'ios') {

								//拉起收银台
								tt.getOrderPayment({
									orderId: res.orderId,
									imId: that.imId,
									success: (res) => {
										console.log('支付成功', res);
										uni.showToast({
											title: "充值成功",
											icon: "success"
										})
										uni.vk.userCenter.getCurrentUserInfo({
											success: async (data) => {
												console.log("data=", data
													.userInfo);
												await vk.vuex.set('$user.userInfo',
													data.userInfo)
												await uni.vk.myfn.updataTime();
												if (item.subject == "单剧会员") {
													console.log('这里触发了3');
													let subject = item.subject
													this.$emit("transfer1",
														subject) //触发transfer方法
												} else {
													console.log('这里触发了2');
													that.$emit("transfer", data
														.userInfo
														.plus_type
													) //触发transfer方法
												}


											}
										});
										//查询订单信息


									},
									fail: (res) => {
										console.log("支付失败", res)
									},

								});

							} else {

								//拉起收银台
								tt.getOrderPayment({
									orderId: res.orderId,
									success: (res) => {
										console.log('支付成功', res);
										uni.showToast({
											title: "充值成功",
											icon: "success"
										})
										uni.vk.userCenter.getCurrentUserInfo({
											success: async (data) => {
												console.log("data=", data);
												console.log("data=", data
													.userInfo);
												await vk.vuex.set('$user.userInfo',
													data.userInfo)
												await uni.vk.myfn.updataTime();
												if (item.subject == "单剧会员") {
													console.log('这里触发了3');
													let subject = item.subject
													this.$emit("transfer1",
														subject) //触发transfer方法
												} else {
													console.log('这里触发了2');
													that.$emit("transfer", data
														.userInfo
														.plus_type
													) //触发transfer方法
												}
											}
										});
										//查询订单信息


									},
									fail: (res) => {
										console.log("支付失败", res)
									},

								});

							}






						},
						fail: (res) => {
							console.log("请求出错", res)
						},
					});

				} else {
					uni.showToast({
						title: "创建订单失败",
						icon: "error"
					})
				}



			},
		}
	}
</script>

<style lang="scss" scoped>
	.boxTemplate {
		width: 730rpx;
		margin: 0 auto;
		display: flex;
		flex-wrap: wrap;

		.Scheme {
			width: 350rpx;
			height: 180rpx;
			margin: 20rpx 0;

			.Schemecontent {
				width: 94%;
				height: 180rpx;
				border-radius: 12rpx;
				margin: 0 auto;
				position: relative;
				background-image: url("@/static/tehui.png");
				background-size: 100% 180rpx;

				view {
					position: absolute;
				}

				.Judge {
					padding: 0px 40rpx;
					text-align: center;
					color: #e5563b;
					background-image: url("@/static/tehuis.png");
					background-size: 100% 100%;
					border-radius: 12rpx 0 12rpx 0;
					font-size: 26rpx;
					font-weight: 600;
				}

				.RechargeAmount {
					font-weight: 600;
					font-size: 36rpx;
					left: 5%;
					top: 25%;
				}

				.GiveBean {
					padding: 0 20rpx;
					font-size: 24rpx;
					font-weight: 600;
					background-color: #f55125;
					color: #fff;
					border-radius: 50rpx;
					left: 40%;
					top: 29%;
				}

				.RechargeText {
					font-size: 28rpx;
					font-weight: 600;
					left: 8%;
					bottom: 23%;
				}

				.PercentageUser {
					color: #e37f75;
					font-size: 24rpx;
					font-weight: 600;
					right: 20rpx;
					bottom: 10rpx;
				}
			}

			.Schemecontents {
				width: 94%;
				height: 180rpx;
				border-radius: 12rpx;
				margin: 0 auto;
				background-color: #fff;
				position: relative;

				view {
					position: absolute;
				}


				.RechargeAmount {
					font-weight: 600;
					font-size: 36rpx;
					left: 3%;
					top: 20%;
				}

				.GiveBean {
					padding: 0rpx 20rpx;
					font-size: 24rpx;
					font-weight: 600;
					background-color: #f55125;
					color: #fff;
					border-radius: 50rpx;
					left: 38%;
					top: 24%;
				}

				.RechargeText {
					font-size: 24rpx;
					font-weight: 600;
					left: 5%;
					bottom: 20%;
				}
			}

			.Schemecontentss {
				width: 94%;
				height: 180rpx;
				border-radius: 14rpx;
				margin: 0 auto;
				position: relative;
				background-image: url("@/static/huiyuan.png");
				background-size: 100% 180rpx;

				view {
					position: absolute;
				}

				.Judge {
					padding: 0px 40rpx;
					text-align: center;
					color: #e5563b;
					background-color: #fafc43;
					border-radius: 12rpx 0 12rpx 0;
					font-size: 26rpx;
					font-weight: 600;
				}

				.RechargeAmount {
					color: #ffffff;
					font-weight: 600;
					font-size: 32rpx;
					left: 5%;
					top: 25%;
				}

				.RechargeText {
					color: #f2e4d8;
					font-size: 28rpx;
					font-weight: 500;
					left: 5%;
					bottom: 20%;
				}

			}
		}
	}

	.top_balance {
		display: flex;
		align-items: center;
		font-size: 32rpx;
		margin: 60rpx 0 20rpx 20rpx;
		width: 680rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.dou {
		color: #fe742c;
		font-weight: 600;
		font-size: 36rpx;
		margin: 0 20rpx 0 0;
	}

	.explanation {
		color: #606060;
		font-size: 22rpx;
		line-height: 40rpx;
		margin-left: 20rpx;
	}

	.ttbuttona {

		background-color: rgba(250, 250, 250, 0);
		position: fixed;
		top: 50rpx;
		right: 30rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 20rpx;
		z-index: 999;
		/* 移除点击时的外部边框 */
	}

	.ttbuttona::after {
		content: "";
		/* 确保内容为空，以保持伪类可见性 */
		border: none;
		/* 去除伪类元素的边框 */
	}
</style>